<?php

// 每天代付统计控制器

namespace app\api\controller;

use app\api\controller\Base;
use think\Db;

class DayPaid extends Base
{

        /**
         * 每天统计一次代付
         */
        public function dayPaid()
        {

                try {
                        // 只允许命令行访问
                        if (PHP_SAPI != 'cli') {
                                return ['code' => 999, 'msg' => '404'];
                        }

                        debug('begin');

                        // 设置多少秒执行一次（默认一天）
                        $interval_time = 50000;

                        // 统计时间（今天跑昨天的数据）
                        $query_time = date('Y-m-d');
                        $statistics_date = date('Y-m-d', (strtotime($query_time) - 3600 * 24 * 1));

                        $map = [];
                        Db::name('payment_merchant_config')
                                ->where($map)
                                ->chunk(100, function ($all) use ($statistics_date, $interval_time) {
                                        foreach ($all as $single) {

                                                $data = [];                       // 统计表数据          
                                                $bank_paid = [];                  // 银行卡代付数据  
                                                $bank_app_id = [];                // 记录银行卡代付的应用ID对应数据
                                                $alipay_paid = [];                // 支付宝代付数据  
                                                $alipay_app_id = [];              // 记录支付宝代付的应用ID对应数据
                                                // 存在跳过
                                                $exist_paid_cash_source = Db::name('payment_paid_cash_source')
                                                        ->where(['merchant_id' => $single['id']])
                                                        ->whereTime('dates', 'between', ["{$statistics_date} 00:00:00", "{$statistics_date} 23:59:59"])
                                                        ->find();

                                                if (!$exist_paid_cash_source) {

                                                        $temp_map = [];
                                                        // 用代付完成时间统计，不会第二天有误
                                                        $temp_map[] = ['update_time', ['>=', strtotime($statistics_date)], ['<', strtotime($statistics_date) + 86400]];

                                                        $temp_map[] = ['merchant_id', '=', $single['id']];

                                                        /* 银行卡代付数据处理 */

                                                        // 创建代付订单数量
                                                        $bank_all_cash_counts = Db::name('payment_order_paid')
                                                                ->where($temp_map)
                                                                ->count();

                                                        // 完成代付订单数量
                                                        $bank_finish_cash_counts = Db::name('payment_order_paid')
                                                                ->where($temp_map)
                                                                ->where(['status' => 2])
                                                                ->count();

                                                        // 创建代付订单金额
                                                        $bank_all_cashs = Db::name('payment_order_paid')
                                                                ->where($temp_map)
                                                                ->sum('cash');

                                                        // 完成代付订单金额
                                                        $bank_finish_cashs = Db::name('payment_order_paid')
                                                                ->where($temp_map)
                                                                ->where(['status' => 2])
                                                                ->sum('cash');

                                                        // 完成代付订单扣除金额
                                                        $bank_finish_deduct_cashs = Db::name('payment_order_paid')
                                                                ->where($temp_map)
                                                                ->where(['status' => 2])
                                                                ->sum('deduct_cash');

                                                        $bank_paid['bank_all_cash_counts'] = $bank_all_cash_counts;
                                                        $bank_paid['bank_finish_cash_counts'] = $bank_finish_cash_counts;
                                                        $bank_paid['bank_all_cashs'] = $bank_all_cashs ? $bank_all_cashs / 100 : 0;
                                                        $bank_paid['bank_finish_cashs'] = $bank_finish_cashs ? $bank_finish_cashs / 100 : 0;
                                                        $bank_paid['bank_finish_deduct_cashs'] = $bank_finish_deduct_cashs ? $bank_finish_deduct_cashs / 100 : 0;
                                                        $bank_paid['bank_poundage'] = ($bank_finish_deduct_cashs - $bank_finish_cashs) / 100;

                                                        // 记录银行卡代付的应用ID
                                                        $bank_all_app_id_array = Db::name('payment_order_paid')
                                                                ->where($temp_map)
                                                                ->distinct(true)
                                                                ->column('app_id');

                                                        if ($bank_all_app_id_array) {
                                                                foreach ($bank_all_app_id_array as $app_id_value) {

                                                                        $app_id_all_counts = Db::name('payment_order_paid')
                                                                                ->where($temp_map)
                                                                                ->where(['app_id' => $app_id_value])
                                                                                ->count();

                                                                        $app_id_finish_counts = Db::name('payment_order_paid')
                                                                                ->where($temp_map)
                                                                                ->where(['app_id' => $app_id_value])
                                                                                ->where(['status' => 2])
                                                                                ->count();

                                                                        $app_id_all_cashs = Db::name('payment_order_paid')
                                                                                ->where($temp_map)
                                                                                ->where(['app_id' => $app_id_value])
                                                                                ->sum('cash');

                                                                        $app_id_finish_cashs = Db::name('payment_order_paid')
                                                                                ->where($temp_map)
                                                                                ->where(['app_id' => $app_id_value])
                                                                                ->where(['status' => 2])
                                                                                ->sum('cash');

                                                                        $app_id_finish_deduct_cashs = Db::name('payment_order_paid')
                                                                                ->where($temp_map)
                                                                                ->where(['app_id' => $app_id_value])
                                                                                ->where(['status' => 2])
                                                                                ->sum('deduct_cash');

                                                                        $bank_app_id[$app_id_value]['all']['cash'] = $app_id_all_cashs ? $app_id_all_cashs / 100 : 0;
                                                                        $bank_app_id[$app_id_value]['all']['count'] = $app_id_all_counts;
                                                                        $bank_app_id[$app_id_value]['finish']['cash'] = $app_id_finish_cashs ? $app_id_finish_cashs / 100 : 0;
                                                                        $bank_app_id[$app_id_value]['finish']['deduct_cash'] = $app_id_finish_deduct_cashs ? $app_id_finish_deduct_cashs / 100 : 0;
                                                                        $bank_app_id[$app_id_value]['finish']['count'] = $app_id_finish_counts;
                                                                }
                                                        }

                                                        /* 支付宝代付数据处理 */

                                                        // 创建代付订单数量
                                                        $alipay_all_cash_counts = Db::name('payment_order_alipay_paid')
                                                                ->where($temp_map)
                                                                ->count();

                                                        // 完成代付订单数量
                                                        $alipay_finish_cash_counts = Db::name('payment_order_alipay_paid')
                                                                ->where($temp_map)
                                                                ->where(['status' => 2])
                                                                ->count();

                                                        // 创建代付订单金额
                                                        $alipay_all_cashs = Db::name('payment_order_alipay_paid')
                                                                ->where($temp_map)
                                                                ->sum('cash');

                                                        // 完成代付订单金额
                                                        $alipay_finish_cashs = Db::name('payment_order_alipay_paid')
                                                                ->where($temp_map)
                                                                ->where(['status' => 2])
                                                                ->sum('cash');

                                                        // 完成代付订单扣除金额
                                                        $alipay_finish_deduct_cashs = Db::name('payment_order_alipay_paid')
                                                                ->where($temp_map)
                                                                ->where(['status' => 2])
                                                                ->sum('deduct_cash');

                                                        $alipay_paid['alipay_all_cash_counts'] = $alipay_all_cash_counts;
                                                        $alipay_paid['alipay_finish_cash_counts'] = $alipay_finish_cash_counts;
                                                        $alipay_paid['alipay_all_cashs'] = $alipay_all_cashs ? $alipay_all_cashs / 100 : 0;
                                                        $alipay_paid['alipay_finish_cashs'] = $alipay_finish_cashs ? $alipay_finish_cashs / 100 : 0;
                                                        $alipay_paid['alipay_finish_deduct_cashs'] = $alipay_finish_deduct_cashs ? $alipay_finish_deduct_cashs / 100 : 0;
                                                        $alipay_paid['alipay_poundage'] = ($alipay_finish_deduct_cashs - $alipay_finish_cashs) / 100;

                                                        // 记录支付宝代付的应用ID
                                                        $alipay_all_app_id_array = Db::name('payment_order_alipay_paid')
                                                                ->where($temp_map)
                                                                ->distinct(true)
                                                                ->column('app_id');

                                                        if ($alipay_all_app_id_array) {
                                                                foreach ($alipay_all_app_id_array as $app_id_value) {

                                                                        $app_id_all_counts = Db::name('payment_order_alipay_paid')
                                                                                ->where($temp_map)
                                                                                ->where(['app_id' => $app_id_value])
                                                                                ->count();

                                                                        $app_id_finish_counts = Db::name('payment_order_alipay_paid')
                                                                                ->where($temp_map)
                                                                                ->where(['app_id' => $app_id_value])
                                                                                ->where(['status' => 2])
                                                                                ->count();

                                                                        $app_id_all_cashs = Db::name('payment_order_alipay_paid')
                                                                                ->where($temp_map)
                                                                                ->where(['app_id' => $app_id_value])
                                                                                ->sum('cash');

                                                                        $app_id_finish_cashs = Db::name('payment_order_alipay_paid')
                                                                                ->where($temp_map)
                                                                                ->where(['app_id' => $app_id_value])
                                                                                ->where(['status' => 2])
                                                                                ->sum('cash');

                                                                        $app_id_finish_deduct_cashs = Db::name('payment_order_alipay_paid')
                                                                                ->where($temp_map)
                                                                                ->where(['app_id' => $app_id_value])
                                                                                ->where(['status' => 2])
                                                                                ->sum('deduct_cash');

                                                                        $alipay_app_id[$app_id_value]['all']['cash'] = $app_id_all_cashs ? $app_id_all_cashs / 100 : 0;
                                                                        $alipay_app_id[$app_id_value]['all']['count'] = $app_id_all_counts;
                                                                        $alipay_app_id[$app_id_value]['finish']['cash'] = $app_id_finish_cashs ? $app_id_finish_cashs / 100 : 0;
                                                                        $alipay_app_id[$app_id_value]['finish']['deduct_cash'] = $app_id_finish_deduct_cashs ? $app_id_finish_deduct_cashs / 100 : 0;
                                                                        $alipay_app_id[$app_id_value]['finish']['count'] = $app_id_finish_counts;
                                                                }
                                                        }

                                                        // 商户之前的余额
                                                        $payment_cash_table = Db::name('payment_cash')
                                                                ->where(['merchant_id' => $single['id']])
                                                                ->find();

                                                        $data['merchant_id'] = $single['id'];                                        // 商户号
                                                        $data['paid_start_price'] = $single['paid_start_price'];                     // 银行卡每次代付开始价格
                                                        $data['paid_rate'] = $single['paid_rate'];                                   // 银行卡每次代付费率
                                                        $data['alipay_paid_start_price'] = $single['alipay_paid_start_price'];       // 支付宝每次代付开始价格
                                                        $data['alipay_paid_rate'] = $single['alipay_paid_rate'];                     // 支付宝代付费率
                                                        $data['bank_paid'] = json_encode($bank_paid);                                // 银行卡代付
                                                        $data['bank_app_id'] = json_encode($bank_app_id);                            // 银行卡代付的订单包括哪些应用ID
                                                        $data['alipay_paid'] = json_encode($alipay_paid);                            // 支付宝代付
                                                        $data['alipay_app_id'] = json_encode($alipay_app_id);                        // 支付宝代付的订单包括哪些应用ID
                                                        $data['before_paid_cash'] = isset($payment_cash_table['paid_cash']) ? $payment_cash_table['paid_cash'] : 0;  // 统计之前的余额
                                                        $data['trade_type'] = 'paid';                                                // 交易类型
                                                        $data['dates'] = $statistics_date . ' 05:00:00';                             // 统计日期
                                                        $data['settlement_type'] = $single['settlement_type'];                       // 结算类型T是0，D是1
                                                        $data['settlement_day'] = $single['settlement_day'];                         // 结算天数
                                                        $data['status'] = $single['status'];                                         // 状态
                                                        $data['create_time'] = time();                                               // 创建时间
                                                        $data['update_time'] = time();                                               // 更新时间
                                                        $data['merchant_config'] = json_encode($single);                             // 商户号配置
                                                        $data['order_id'] = date('ymdHis', strtotime($data['dates'])) . random(8);   // 平台订单号
                                                        // 商户金额来源统计表
                                                        try {
                                                                Db::name('payment_paid_cash_source')
                                                                        ->insert($data);
                                                        } catch (\Exception $e) {

                                                                // 商户每天来源订单数据
                                                                payment_error_log(700002, '商户插入每天代付统计数据失败', $data);
                                                        }
                                                } else {

                                                        // 已经存在
                                                        payment_error_log(700001, "商户号已经跑过指定代付日期数据{$statistics_date}", $single);
                                                }

                                                unset($single);
                                        }
                                }, 'id', 'desc');

                        debug('end');
                        payment_error_log(700003, debug('begin', 'end', 2), debug('begin', 'end', 'm'));
                } catch (\Exception $e) {
                        payment_error_log(700000, $e->getMessage());
                        return ['code' => 999, 'msg' => '404'];
                }
        }
}
